<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="icon" href="${pageContext.request.contextPath}/lib/static/login/images/favicon.ico">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/layui/css/layui.css" media="all">
    <script src="${pageContext.request.contextPath}/lib/layui/layui.js" charset="utf-8"></script>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>用户管理</legend>
        </fieldset>
    </div>
    <hr class="layui-bg-red">

    <!--按钮及查询框组-->
    <div class="layui-row">
        <div class="layui-col-md-offset1">
            <form class="layui-form">
                <div class="layui-inline">
                    <input class="layui-input" name="criteria" autofocus placeholder="用户名 / 姓名">
                </div>
                <button class="layui-btn layuiadmin-btn-admin" lay-submit="" lay-filter="search">
                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
            </form>
        </div>
    </div>

    <table class="layui-hide" id="userTable" lay-filter="userMonitor"></table>


    <script type="text/html" id="userToolbar">
        <div class="layui-btn-container">
            <shiro:hasPermission name="sys:user:delete">
                <button class="layui-btn layui-btn-sm" lay-event="delByIds">删除</button>
            </shiro:hasPermission>
            <shiro:hasPermission name="sys:user:add">
                <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
            </shiro:hasPermission>
        </div>
    </script>

    <script type="text/html" id="userBar">
        <shiro:hasPermission name="sys:user:edit">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="sys:user:delete">
            <a class="layui-btn layui-btn-xs" lay-event="del">删除</a>
        </shiro:hasPermission>
        <shiro:hasPermission name="sys:user:accredit">
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="accredit">授予角色</a>
        </shiro:hasPermission>
    </script>


    <script>
        var baseUrl = '${pageContext.request.contextPath}/sys/user/';

        /*发送ajax请求访问后台*/
        function sendAjaxPostReq($, param, tableUserIns, method) {
            $.post(
                baseUrl + method,
                param,
                function (result) {
                    if (result.code == 0) {
                        layer.msg(result.msg, {icon: 1});
                        /*刷新表格数据*/
                        tableUserIns.reload({
                            url: baseUrl + "get"
                        });
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                "json"
            );
        }

        /*公用根据id或ids删除用户*/
        function deleteUserByIds($, ids, tableUserIns, len) {
            /*多项删除时没有选择数据时给出提示*/
            if (len < 1) {
                layer.alert('请至少选择一条您要删除的数据', {
                    skin: 'layui-layer-molv'
                    , closeBtn: 0
                });
                return;
            }
            layer.confirm("您选中了" + len + "条数据，确认删除？", function (index) {
                sendAjaxPostReq($, {ids: ids}, tableUserIns, "deleteByIds");
                layer.close(index);
            });
        }

        layui.use(['jquery', 'table', 'form'], function () {
            var $ = layui.$
            var table = layui.table;
            var form = layui.form;
            /*数据表格*/
            var tableUserIns = table.render({
                elem: '#userTable'
                , title: '用户数据'
                , defaultToolbar: ['filter']
                , toolbar: '#userToolbar'
                , url: baseUrl + 'get'
                /*修改默认向后台传递的页码、大小参数名 @ming*/
                , request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                , height: 'full-150'
                , cols: [[
                    {type: 'numbers'}
                    , {type: 'checkbox'}
                    , {field: 'id', title: '用户编号', align: 'center'}
                    , {field: 'deptName', title: '部门名称', align: 'center'}
                    , {field: 'username', title: '用户名', align: 'center'}
                    , {field: 'name', title: '姓名', align: 'center'}
                    , {field: 'mobile', title: '手机号', align: 'center', minWidth: 120}
                    , {field: 'email', title: '邮箱', align: 'center', minWidth: 165}
                    , {field: 'addUser', title: '添加人', align: 'center'}
                    , {
                        field: 'addTime',
                        title: '添加时间',
                        minWidth: 160,
                        align: 'center',
                        sort: true,
                        templet: '<div>{{layui.laytpl.toDateString(d.addTime)}}</div>'
                    }
                    , {field: 'updateUser', title: '修改人', align: 'center'}
                    , {
                        field: 'updateTime',
                        title: '修改时间',
                        minWidth: 160,
                        align: 'center',
                        sort: true,
                        templet: '<div>{{layui.laytpl.toDateString(d.updateTime)}}</div>'
                    }
                    , {field: 'remark', title: '备注', align: 'center', minWidth: 160}
                    , {fixed: 'right', title: '操作', toolbar: '#userBar', width: 200, align: 'center'}
                ]]
                , page: {
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                    , groups: 5
                }
                , parseData: function (res) { /*重新解析json*/
                    var data = res.data;
                    /*显示部门名称*/
                    $.each(data, function (index, user) {
                        user.deptName = user.dept.deptName
                    });
                    return res;
                }
            })
            //时间戳处理
            layui.laytpl.toDateString = function (d, format) {
                /*当时间为null时返回空字符串*/
                if (!d) {
                    return "";
                }
                var date = new Date(d)
                    , ymd = [
                    this.digit(date.getFullYear(), 4)
                    , this.digit(date.getMonth() + 1)
                    , this.digit(date.getDate())
                ]
                    , hms = [
                    this.digit(date.getHours())
                    , this.digit(date.getMinutes())
                    , this.digit(date.getSeconds())
                ];
                format = format || 'yyyy-MM-dd HH:mm:ss';
                return format.replace(/yyyy/g, ymd[0])
                    .replace(/MM/g, ymd[1])
                    .replace(/dd/g, ymd[2])
                    .replace(/HH/g, hms[0])
                    .replace(/mm/g, hms[1])
                    .replace(/ss/g, hms[2])
            };
            //数字前置补零
            layui.laytpl.digit = function (num, length, end) {
                var str = '';
                num = String(num);
                length = length || 2;
                for (var i = num.length; i < length; i++) {
                    str += '0';
                }
                return num < Math.pow(10, length) ? str + (num | 0) : num;
            };

            /*新增/修改 iframe层公用方法*/
            function openUserEditLayer(title, method, user) {
                layer.open({
                    content: [baseUrl + "user_edit"],
                    type: 2,
                    title: '<h2>' + title + '</h2>',
                    maxmin: true,
                    shadeClose: true, //点击遮罩关闭层
                    offset: '50px',
                    area: ['800px', '530px'],
                    closeBtn: 2,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        /*按method绑定 新增或者修改事件*/
                        body.find("[lay-submit]").attr("lay-filter", method);
                        /*回显数据 start*/
                        if (method == 'editUser') {
                            /*修改时保存id到隐藏域*/
                            body.find("input[name='id']").val(user.id);
                            /*修改时保存部门id到隐藏域*/
                            body.find("input[name='deptId']").val(user.deptId);
                            /*修改时 移除密码输入，禁止修改密码*/
                            body.find("input[name='password']").parent().parent().remove();
                            body.find("input[name='username']").val(user.username).attr("readonly", "");
                            body.find("input[name='name']").val(user.name);
                            body.find("input[name='mobile']").val(user.mobile);
                            body.find("input[name='email']").val(user.email);
                            body.find("input[name='remark']").val(user.remark);
                            if (user.valid == 0) {
                                body.find("input[name='valid']").attr("checked", "checked");
                            }

                            body.find("button[type='reset']").remove();
                        }
                        /*回显数据 end*/
                        layer.iframeAuto(index);
                        return false;
                    }
                });
            }

            //头工具栏事件
            table.on('toolbar(userMonitor)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'delByIds':
                        /*获得要删除的ids*/
                        var data = checkStatus.data;
                        var ids = [];
                        $.each(data, function (index, value) {
                            var id = value.id;
                            ids.push(id);
                        });
                        /*根据id删除数据*/
                        deleteUserByIds($, ids.toString(), tableUserIns, data.length);
                        break;
                    case 'add':
                        openUserEditLayer("添加用户", "saveUser");
                        break;
                }
            });
            //监听行工具事件
            table.on('tool(userMonitor)', function (obj) {
                var data = obj.data;

                if (obj.event === 'accredit') {
                    layer.open({
                        content: [baseUrl + 'user_accredit'],
                        type: 2,
                        title: '<h2>为用户授予角色</h2>',
                        maxmin: true,
                        shadeClose: true,
                        offset: '80px',
                        area: ['800px', '520px'],
                        closeBtn: 2,
                        success: function (layero, index) {
                            var body = layer.getChildFrame('body', index);
                            body.find('#id').val(data.id);
                            return false;
                        }
                    });
                } else if (obj.event === 'edit') {
                    var editUserId = data.id;
                    $.post(
                        baseUrl + "getUserById",
                        {id: editUserId},
                        function (result) {
                            var user = result;
                            openUserEditLayer("修改用户", "editUser", user);
                        },
                        "json"
                    );
                    /*单项删除功能*/
                } else if (obj.event === 'del') {
                    deleteUserByIds($, data.id, tableUserIns, 1);
                }
            });
            /*查询功能*/
            form.on('submit(search)', function (data) {
                tableUserIns.reload({
                    url: baseUrl + 'get'
                    , method: "post" /*解决参数传递中文乱码*/
                    , where: data.field
                });
                return false;
            });
        });
    </script>
</div>
</body>
</html>